package com.taptech.doufu.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.taptech.doufu.R;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.bean.ConfigBean;
import com.taptech.doufu.bean.ConfigGsonBean;
import com.taptech.doufu.bean.ScreenSplash;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.constant.ContentType;
import com.taptech.doufu.constant.DeepLinkParam;
import com.taptech.doufu.constant.DeepLinkType;
import com.taptech.doufu.constant.EventKey;
import com.taptech.doufu.constant.HomePageIndex;
import com.taptech.doufu.constant.InterestType;
import com.taptech.doufu.constant.SPKey;
import com.taptech.doufu.event.BaseEventBusBean;
import com.taptech.doufu.event.EventBusBindPhone;
import com.taptech.doufu.event.EventBusChangeTheme;
import com.taptech.doufu.event.EventBusCollectUnRead;
import com.taptech.doufu.event.EventBusConstant;
import com.taptech.doufu.event.EventBusLoginout;
import com.taptech.doufu.event.EventBusSycnHistoryData;
import com.taptech.doufu.manager.NovelEditManager;
import com.taptech.doufu.manager.UserLogManager;
import com.taptech.doufu.net.retrofit.api.ApiClient;
import com.taptech.doufu.net.retrofit.api.BaseSubscriber;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.receiver.CompetencePupopWindowReceiver;
import com.taptech.doufu.services.PersonalNoteService;
import com.taptech.doufu.services.history.ReadHistoryUtil;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.ui.activity.me.PhoneBindActivity;
import com.taptech.doufu.ui.activity.weex.DialogWeexActivity;
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity;
import com.taptech.doufu.ui.dialog.PermissionTipDialog;
import com.taptech.doufu.ui.dialog.YouthModelDialog;
import com.taptech.doufu.ui.fragment.DFBookshelfFragment;
import com.taptech.doufu.ui.fragment.DFHomeFragment;
import com.taptech.doufu.ui.fragment.NewHomeFragment2;
import com.taptech.doufu.ui.fragment.weex.NotifyFragment;
import com.taptech.doufu.ui.fragment.weex.PersonalCenterFragment;
import com.taptech.doufu.ui.view.TransitionImageView;
import com.taptech.doufu.umeng.UVerifyManager;
import com.taptech.doufu.umeng.push.InAppMessageKey;
import com.taptech.doufu.umeng.push.PushManager;
import com.taptech.doufu.util.ActivityUtil;
import com.taptech.doufu.util.AsyncImageLoader;
import com.taptech.doufu.util.CacheUtil;
import com.taptech.doufu.util.DeviceUtil;
import com.taptech.doufu.util.GlideUtil;
import com.taptech.doufu.util.HttpRequestUtil;
import com.taptech.doufu.util.JsonDataUtil;
import com.taptech.doufu.util.NotifyUtil;
import com.taptech.doufu.util.ScreenUtil;
import com.taptech.doufu.util.ScreenUtil2;
import com.taptech.doufu.util.SharedPreferenceUtil;
import com.taptech.doufu.util.SignCheckUtil;
import com.taptech.doufu.util.StartActivityUtils;
import com.taptech.doufu.util.StringUtil;
import com.taptech.doufu.util.TMAnalysis;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.util.TimeDateFunction;
import com.taptech.doufu.util.UpdateUtil;
import com.taptech.doufu.util.WMUrlRequest_1_1;
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences;
import com.taptech.doufu.weex.TFHotUpdateUtil;
import com.taptech.doufu.weex.notification.QLXNotificationCenter;
import com.taptech.doufu.weex.notification.QLXNotificationListener;
import com.umeng.analytics.MobclickAgent;
import com.umeng.umlink.MobclickLink;
import com.umeng.umlink.UMLinkListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

public class MainHomeActivity extends DiaobaoBaseActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
    public static  MainHomeActivity  mainInstance = null;
    public final static int REQUEST_READ_PHONE_STATE = 3;
    private Fragment[] fragments = new Fragment[4];
    private String fragments_name[] = {"novelFragment", "bookshelfFragment" , "notifyFragment", "personalFragment"};
    public int currentTabIndex = 0;
    private int loginIndex = 0;
    View bottomlayout[] = new View[4];
    View[] bottomImg = new View[4];
    ImageView[] bottomTv_upimage = new ImageView[4];
    private static final int imagDrawPress[] = {R.drawable.icon_home_pressed, R.drawable.icon_shelf_pressed, R.drawable.icon_message_pressed, R.drawable.icon_mine_pressed};
    private static final int imagDraw[] = {R.drawable.icon_home_default,R.drawable.icon_shelf_default,  R.drawable.icon_message_default, R.drawable.icon_mine_default};
    private TransitionImageView mTransitionImageView;
    private LinearLayout mTransitionRelativeLayout;
    private TranslateAnimation hideTranslateAnimation;
    private RelativeLayout mTransitionBackLayout;
    protected SharedPreferences version;
    public static MainHomeActivity instance;
    private FrameLayout flGDT;

    private TextView unreadNotify;
    private TextView unreadBookshelf;
    private boolean isFinish = false;
    private View layGuide;
    private LinearLayout line_mainhome_bottom2,main_bottom;


    // 通用的广播接收者
//    CompetencePupopWindowReceiver mainHomeBroadcastReceiver;
    // for fun
    ImageView funImg;


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void openYouthModel(BaseEventBusBean event){
        if (event != null && EventKey.YOUTH_MODEL.equals(event.getTag())) {
            setYouthModel();
        }
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
    }





    private boolean signCheck() {
        SignCheckUtil signCheckUtil = new SignCheckUtil(this, "MD5");
        if (!signCheckUtil.check()) {
            //签名不正确
            new AlertDialog.Builder(this).setCancelable(false).setMessage("签名不正确，请前往应用商店下载正版 app").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            }).show();
        }
        return signCheckUtil.check();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        boolean isSignCheck = signCheck();
        if (!isSignCheck) {
            return;
        }
        UVerifyManager.getInstance().verifyLoginFirstOpenApp();
        mainInstance = this;
        // TODO Auto-generated method stub
        if (savedInstanceState != null) {
            fragments[0] =  getSupportFragmentManager().findFragmentByTag(fragments_name[0]);
            fragments[1] =  getSupportFragmentManager().findFragmentByTag(fragments_name[1]);
            fragments[2] =  getSupportFragmentManager().findFragmentByTag(fragments_name[2]);
            fragments[3] =  getSupportFragmentManager().findFragmentByTag(fragments_name[3]);
//            fragments[4] =  getSupportFragmentManager().findFragmentByTag(fragments_name[4]);
        }
        {
            setContentView(R.layout.activity_main_home_one);
            EventBus.getDefault().register(this);
            setStatusBarFullTransparent();
            Constant.activityRun = true;
            instance = this;
            flGDT = (FrameLayout) findViewById(R.id.flGDT);
            if (Build.VERSION.SDK_INT >= 19) {
                flGDT.setPadding(0,ScreenUtil.getStatusHeight(this),0,0);
            }
            line_mainhome_bottom2 = (LinearLayout) findViewById(R.id.line_mainhome_bottom2);
            main_bottom = findViewById(R.id.main_bottom);
            viewTopLine2 =  findViewById(R.id.view_mainhome_show);
            bottomlayout[0] = findViewById(R.id.layout_container_novel);//小说
            bottomlayout[1] = findViewById(R.id.layout_container_bookshelf);//漫画
//            bottomlayout[2] = findViewById(R.id.layout_container_find);//发现
            bottomlayout[2] = findViewById(R.id.layout_container_notify);//书架
            bottomlayout[3] = findViewById(R.id.layout_container_personal);//我的

            bottomImg[0] =  findViewById(R.id.img_home_novel);
            bottomImg[1] =  findViewById(R.id.img_home_bookshelf);
//            bottomImg[2] =  findViewById(R.id.img_home_find);
            bottomImg[2] =  findViewById(R.id.img_home_notify);
            bottomImg[3] =  findViewById(R.id.img_home_personal);

            bottomTv_upimage[0] = (ImageView) findViewById(R.id.img_home_novel_up);
            bottomTv_upimage[1] = (ImageView) findViewById(R.id.img_home_bookshelf_up);
//            bottomTv_upimage[2] = (ImageView) findViewById(R.id.img_home_find_up);
            bottomTv_upimage[2] = (ImageView) findViewById(R.id.img_home_notify_up);
            bottomTv_upimage[3] = (ImageView) findViewById(R.id.img_home_personal_up);
            if (fragments[0] == null) {
                fragments[0] = new DFHomeFragment();
            }
            if (fragments[2] == null) {
                fragments[2] = new NotifyFragment();
            }
            if (fragments[3] == null && !WeMediaApplication.isNeedRefreshWeex) {
                fragments[3] = new PersonalCenterFragment();
            }
            // 添加显示第一个fragment
            if (Constant.activityRun) {
                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                ft.add(R.id.fragment_container, fragments[2], fragments_name[2]);
                if (fragments[3] != null) {
                    ft.add(R.id.fragment_container, fragments[3], fragments_name[3]);
                    ft.add(R.id.fragment_container, fragments[0], fragments_name[0]).show(fragments[0]).hide(fragments[2]).hide(fragments[3]).commitAllowingStateLoss();
                }else{
                    ft.add(R.id.fragment_container, fragments[0], fragments_name[0]).show(fragments[0]).hide(fragments[2]).commitAllowingStateLoss();
                }
            }
            unreadNotify = (TextView) findViewById(R.id.unreadNotify);

            unreadBookshelf = (TextView) findViewById(R.id.unreadBookshelf);
            mTransitionImageView = (TransitionImageView) findViewById(R.id.tiv_main_tab_transition);
            mTransitionRelativeLayout = (LinearLayout) findViewById(R.id.rl_main_tab_transiton);
            mTransitionBackLayout = (RelativeLayout) findViewById(R.id.v_main_tab_transition_back_layout);
            mTransitionBackLayout.setVisibility(View.GONE);
            mTransitionBackLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    hideTransitionAd(0);
                }
            });
            version = getSharedPreferences(Constant.Version.NAME, Context.MODE_PRIVATE);
            new Handler().postDelayed(new Runnable() {
                @SuppressWarnings("deprecation")
                @Override
                public void run() {
                    if (mTransitionImageView.getVisibility() == View.VISIBLE) {
                        hideTransitionAd(3 * 1000);
                    }
                }
            }, 2000);

            refreshScreenSplash();
            //初始化用户阅读文章顺序
            AccountService.getInstance().setUserReadOrders(SharedPreferenceUtil.getLocalOrderData(this));
            changeBottom();
            DFBookshelfFragment.getCollectUnRead(this);
        }
        handleUMLinkURI(getIntent());
        // for fun
        funImg = (ImageView) findViewById(R.id.joke_img);
        //创建桌面快捷方式
        ActivityUtil.getShortcutToDesktopIntent(MainHomeActivity.this);
        //同步阅读记录
        ReadHistoryUtil.uploadDBTable();
        QLXNotificationCenter.getInstance().addNotify("kTFUserDidLoginCompleteNotification", this, new QLXNotificationListener() {
            @Override
            public void notify(String event, Object data) {
                //同步阅读记录
                ReadHistoryUtil.uploadDBTable();
                getConfig(false);
                //更新书架轮播图
                BaseEventBusBean eventBus = new BaseEventBusBean();
                eventBus.setTag(EventBusConstant.TAG_BOOK_SHELF);
                EventBus.getDefault().post(eventBus);
                NovelEditManager.getInstance().uploadAllData();
            }
        });

        QLXNotificationCenter.getInstance().addNotify("kTFUserDidLogOutCompleteNotification", this, new QLXNotificationListener() {
            @Override
            public void notify(String event, Object data) {
                //退出登录
                ConfigBean.Buoy buoy = new ConfigBean.Buoy();
                buoy.setVisible(false);
                setBuoy(buoy);
            }
        });

        HashMap<String, String> map = new HashMap<>();
        map.put("about", "home");
        NotifyUtil.toasDialog(map);
        NovelEditManager.getInstance().uploadAllData();
        setYouthModel();
    }


    private void checkYouthModelTip() {

        String pwd = DiaoBaoSharedPreferences.getSharedPreferencesValueToString(SPKey.YOUTH_MODEL_PWD, this, "");
        if (pwd != null && pwd.length() > 0) {
            //开启青少年模式后，需要检测
            int hour = TimeDateFunction.toTimeMM(TimeDateFunction.getCurrTime());
            if (hour >= 22 || hour < 6) {
                //弹出防沉迷提示页面
                YouthModelTipActivity.Companion.startActivity(this);
            }else{
                IntentFilter filter = new IntentFilter();
                filter.addAction(Intent.ACTION_TIME_TICK);
                filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
                registerReceiver(mIntentReceiver, filter, null, null);
            }
        }
        //(2)单日使用时长超过触发时间60分钟，弹出防沉迷提示
    }

    private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_TIME_TICK) || action.equals(Intent.ACTION_TIMEZONE_CHANGED)) {
                String time = TimeDateFunction.toTime(TimeDateFunction.getCurrTime());
                if ("22:00:00".equals(time)) {
                    //弹出防沉迷提示页面
                    YouthModelTipActivity.Companion.startActivity(getThisActivity());
                }
            }
        }
    };



    private void toastYouthModeDialog() {
        checkYouthModelTip();
        //未开启青少年模式 && 每天弹出一次
        String pwd = DiaoBaoSharedPreferences.getSharedPreferencesValueToString(SPKey.YOUTH_MODEL_PWD, this, "");
        if (!(pwd != null && pwd.length() > 0)) {
            long toastDialogTime = DiaoBaoSharedPreferences.getSharedPreferencesValueToLong(SPKey.YOUTH_MODEL_DIALOG_TIME, this, 0);
            long currTime = TimeDateFunction.getCurrTime();
            if (currTime - toastDialogTime > 24*60*60*1000){ //每天弹出一次
                DiaoBaoSharedPreferences.setSharedPreferencesValueToLong(SPKey.YOUTH_MODEL_DIALOG_TIME,currTime,this);
                YouthModelDialog dialog = new YouthModelDialog(this);
                dialog.show();
            }
        }
    }

    /**
     * 设置青少年模式
     */
    private void setYouthModel() {
        String pwd = DiaoBaoSharedPreferences.getSharedPreferencesValueToString(SPKey.YOUTH_MODEL_PWD, this, "");
        if (pwd != null && pwd.length() > 0) {
            //开启了青少年模式
            main_bottom.setVisibility(View.GONE);
        }else{
            main_bottom.setVisibility(View.VISIBLE);
        }
    }


    private void getConfig(final boolean showDialog) {
        ApiClient.getInstance().setUseCache(false).getService().getGlobalConfig(
                "", DeviceUtil.isSimulator() ? 1 : 0)
                .compose(RxJavaHelper.<ConfigGsonBean>observeOnMainThread(this))
                .subscribe(new BaseSubscriber<ConfigGsonBean>(){
                    @Override
                    public void onNext(ConfigGsonBean configGsonBean) {
                        super.onNext(configGsonBean);
                        if (configGsonBean != null && configGsonBean.getData() != null) {
                            final ConfigBean.PupUp  pupUp = configGsonBean.getData().getPop_up();
                            if (pupUp != null && pupUp.isVisible()) {
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (showDialog){
                                            boolean showDialog = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean(
                                                    "show_home_dialog_" + pupUp.getId(), MainHomeActivity.this, true);
                                            if (showDialog){
                                                DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(
                                                        "show_home_dialog_" + pupUp.getId(),false,MainHomeActivity.this);
                                                HashMap<String, Object> map = new HashMap<>();
                                                map.put("banner_img",pupUp.getImage());
                                                map.put("object_type", pupUp.getObject_type());
                                                map.put("banner_link", pupUp.getUrl());
                                                String url = "vue/common/TFGlobalPopupBanner.js?present=1";
                                                DialogWeexActivity.startActivity(MainHomeActivity.this,url,map);
                                            }else{
                                                toastYouthModeDialog();
                                            }
                                        }
                                    }
                                }, 500);
                            }else{
                                setGuideView();
                            }
                            ConfigBean.Buoy buoy = configGsonBean.getData().getBuoy();
                            setBuoy(buoy);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);

                    }
                });

    }


    private void handleUMLinkURI(Intent intent) {
        MobclickLink.handleUMLinkURI(this, intent.getData(), new UMLinkListener() {
            @Override
            public void onLink(String s, HashMap<String, String> hashMap) {
                try {
                    if (hashMap != null && hashMap.containsKey(DeepLinkParam.DL_TYPE)) {
                        String type = hashMap.get(DeepLinkParam.DL_TYPE);
                        String id = hashMap.get(DeepLinkParam.DL_ID);
                        String url = hashMap.get(DeepLinkParam.DL_URL);
                        if (String.valueOf(DeepLinkType.DL_NOVEL_DETAIL_PAGE).equals(type)) {
                            NovelDetailsActivity.Companion.startActivity(MainHomeActivity.this,id);
                        } else if (String.valueOf(DeepLinkType.DL_WEB_PAGE).equals(type)) {
                            BrowseActivity.startActivity(MainHomeActivity.this,url);
                        }else if (String.valueOf(DeepLinkType.DL_WEEX_PAGE).equals(type)) {
                            SimpleWeexActivity.startActivity(MainHomeActivity.this,url,hashMap);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onInstall(HashMap<String, String> hashMap, Uri uri) {

            }

            @Override
            public void onError(String s) {

            }
        });
    }



    private void setBuoy(ConfigBean.Buoy buoy) {
        if (fragments.length>0 && fragments[0] instanceof DFHomeFragment){
            ((DFHomeFragment)fragments[0]).setBuoy(buoy);
        }
    }

    /**
     * 引导页面
     */
    private void setGuideView() {
        layGuide = findViewById(R.id.layGuide);
        layGuide.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                layGuide.setVisibility(View.GONE);
                DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(SPKey.HOME_GUIDE,true,MainHomeActivity.this);
            }
        });
//        boolean hasShowGuide = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean(SPKey.HOME_GUIDE, this, false);
//        if (hasShowGuide) {
//            layGuide.setVisibility(View.GONE);
//            toastYouthModeDialog();
//        }else{
//            layGuide.setVisibility(View.VISIBLE);
//        }
        //直接隐藏
        layGuide.setVisibility(View.GONE);
        toastYouthModeDialog();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCollectCountUnRead(EventBusCollectUnRead event) {
        if (event != null && !TextUtils.isEmpty(event.getTag()) && event.getTag().equals(EventBusCollectUnRead.TAG_BOOK_SHELF)) {
            if (event.isShow()) {
                unreadBookshelf.setVisibility(View.VISIBLE);
            }else{
                unreadBookshelf.setVisibility(View.GONE);
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBindPhone(EventBusBindPhone eventBusBindPhone) {
        if (eventBusBindPhone != null) {
            //登录了但没绑定手机
            if (AccountService.getInstance().isLogin()) {
                //强制绑定手机号
                String mobile = AccountService.getInstance().getBaseAccount().getMobile();
                if (mobile == null || mobile.isEmpty()) {
                    //手机号为空注销登录
                    logout();
                    AccountService.getInstance().jumpToLogin();
                }
            }
        }
    }

    private void logout() {
        EventBusCollectUnRead.clearUnRead();
        AccountService.getInstance().clearAccount();
        AccountService.getInstance().setAccountBack(true);
        EventBusLoginout eventBusLoginout = new EventBusLoginout();
        eventBusLoginout.setTag(EventBusLoginout.tag);
        EventBus.getDefault().post(eventBusLoginout);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onChangeTheme(EventBusChangeTheme event) {
        if (event != null && !TextUtils.isEmpty(event.getTag()) && event.getTag().equals(EventBusChangeTheme.TAG_CHANGE_THEME)) {
            if (WeMediaApplication.getInstance().isDayNightMode_Night) {
                changeModeNight();
            } else {
                changeModeDay();
            }
            changeBottom();
            for (int i = 0; i < fragments.length - 1; i++) {
                if (fragments[i] instanceof DFHomeFragment) {
                    DFHomeFragment dfHomeFragment = (DFHomeFragment) fragments[i];
                    dfHomeFragment.changeThemeWithColorful();
                }  else if (fragments[i] instanceof DFBookshelfFragment) {
                    DFBookshelfFragment dfBookshelfFragment = (DFBookshelfFragment) fragments[i];
                    dfBookshelfFragment.changeThemeWithColorful();
                }
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSycnFailData(EventBusSycnHistoryData event) {
        if (event != null && !TextUtils.isEmpty(event.getTag()) && event.getTag().equals(EventBusSycnHistoryData.tag)) {
            ReadHistoryUtil.checkSycnFailData();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleUMLinkURI(intent);
        int index = intent.getIntExtra("index", 0);
        if(fragments!=null && index > fragments.length-1){
            index = 0;
        }
        switchFragment(index);
    }

    /**
     * 当前页面回到顶部
     * @param index
     */
    private void scrollToTop(int index){
        if (index == 0) {
            //首页
            if (fragments[0] != null && fragments[0] instanceof DFHomeFragment) {
                ((DFHomeFragment)fragments[0]).scrollToTop();
            }
        }
    }

    private void switchFragment(int index) {
        try{
            loginIndex = 0;
            if (currentTabIndex == index) {
                scrollToTop(index);
                return;
            }
            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            if (trx == null) {
                return;
            }
            if (fragments[index] == null) {
                if (index == 0) {
                    fragments[0] = new DFHomeFragment();
                    trx.add(R.id.fragment_container, fragments[0], fragments_name[0]);
                } else if (index == 1) {
                    fragments[1] = new DFBookshelfFragment();
                    trx.add(R.id.fragment_container, fragments[1], fragments_name[1]);
                    DFBookshelfFragment.getCollectUnRead(this);
                }
//                else if (index == 2) {
//                    fragments[2] = new NewHomeFragment2();
//                    trx.add(R.id.fragment_container, fragments[2], fragments_name[2]);
//                }
                else if (index == 2) {
                    fragments[2] = new NotifyFragment();
                    trx.add(R.id.fragment_container, fragments[2], fragments_name[2]);
                }else if (index == 3) {
                    fragments[3] = new PersonalCenterFragment();
                    trx.add(R.id.fragment_container, fragments[3], fragments_name[3]);
                }
            } else {
                if(index == 0){
                    DFHomeFragment dfHomeFragment = (DFHomeFragment)fragments[index];
                    dfHomeFragment.changeModelBg();
                } else if (index == 1) {
                    DFBookshelfFragment.getCollectUnRead(this);
                } else if (index == 2){
                    NotifyFragment.refrush();
                }
            }

            Fragment hideFragment = fragments[currentTabIndex];
            Fragment showFragement = fragments[index];
            if (showFragement != null) {
                if (hideFragment != null) {
                    trx.hide(hideFragment);
                    trx.show(showFragement).commit();
                }else{
                    trx.replace(R.id.fragment_container, showFragement, fragments_name[index]).commit();
                }
                currentTabIndex = index;
                changeBottom();
            }

            DFHomeFragment dfHomeFragment = (DFHomeFragment)fragments[0];
            if (dfHomeFragment != null) {
                if (index == 0) {
                    dfHomeFragment.startSpeaker();
                }else{
                    dfHomeFragment.stopSpeaker();
                }
            }

            if(index == 4){
                QLXNotificationCenter.getInstance().postNotify("TFPersonCenterPageDidSelect",null);//点击个人中心通知 必须通知
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
   private int selCurrTitleColorNight = WeMediaApplication.getInstance().getResources().getColor(R.color.theme_main_dark);
   private int nomalCurrTitleColorNight = WeMediaApplication.getInstance().getResources().getColor(R.color.text_dark);

    private int selCurrTitleColor = Color.parseColor("#fe6e6e");
    private int nomalCurrTitleColor = Color.parseColor("#737373");
    private void changeBottom() {
        int currTitleColor;
        for (int i = 0; i < bottomlayout.length ; i++) {
            if (i == currentTabIndex) {
                if(WeMediaApplication.getInstance().isDayNightMode_Night){
                    currTitleColor = selCurrTitleColorNight;
                }else {
                    currTitleColor = selCurrTitleColor;
                }
                bottomTv_upimage[i].setImageResource(imagDrawPress[i]);
            } else {
                if(WeMediaApplication.getInstance().isDayNightMode_Night){
                    currTitleColor = nomalCurrTitleColorNight;
                }else {
                    currTitleColor = nomalCurrTitleColor;
                }
                bottomTv_upimage[i].setImageResource(imagDraw[i]);
            }
            ((TextView) bottomImg[i]).setTextColor(currTitleColor);
        }
    }

    public void onTabClicked(View v) {
        switch (v.getId()) {
            case R.id.layout_container_novel://小说
            case R.id.img_home_novel:
                switchFragment(0);
                UserLogManager.addLog(UserLogManager.LOG_EVENT_NAME_FIRST_PAGE_HOME);
                TMAnalysis.event(MainHomeActivity.this, "4_1_NOVEL");
                break;
//            case R.id.layout_container_find://发现
//            case R.id.img_home_find:
//                UserLogManager.addLog(UserLogManager.LOG_EVENT_NAME_FIRST_PAGE_COMMUNITY);
//                TMAnalysis.event(MainHomeActivity.this, "4_1_FIND");
//                switchFragment(2);
//                break;
            case R.id.layout_container_bookshelf://书架
            case R.id.img_home_bookshelf:
                UserLogManager.addLog(UserLogManager.LOG_EVENT_NAME_FIRST_PAGE_BOOKSHELF);
                TMAnalysis.event(MainHomeActivity.this, "4_1_bookshelf");
                switchFragment(1);
                break;
            case R.id.layout_container_notify:
            case R.id.img_home_notify://通知
                UserLogManager.addLog(UserLogManager.LOG_EVENT_NAME_FIRST_PAGE_MESSAGE);
                TMAnalysis.event(MainHomeActivity.this, "4_1_notify");
                switchFragment(2);
                break;
            case R.id.layout_container_personal://个人
            case R.id.img_home_personal:
                UserLogManager.addLog(UserLogManager.LOG_EVENT_NAME_FIRST_PAGE_MINE);
                switchFragment(3);
                break;
            default:
                break;
        }
    }




    /**
     * 当 SSO 授权 Activity 退出时，该函数被调用。
     *
     * @see {@link Activity#onActivityResult}
     */
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        MobclickAgent.onResume(this);
        if (!AccountService.getInstance().isLogin()) {
            loginIndex = 0;
        } else {
            if (loginIndex != 0) {
                switchFragment(loginIndex);
            }
        }
    }

    public View viewTopLine2;

    public void changeModeNight() {
        unreadBookshelf.setBackgroundResource(R.drawable.cycle_red_night);
        unreadNotify.setBackgroundResource(R.drawable.cycle_red_night);
        line_mainhome_bottom2.setBackgroundColor(Color.rgb(33, 34, 34));
        viewTopLine2.setBackgroundColor(getResources().getColor(R.color.sep_dark));
    }

    public void changeModeDay() {
        unreadBookshelf.setBackgroundResource(R.drawable.cycle_red);
        unreadNotify.setBackgroundResource(R.drawable.cycle_red);
        line_mainhome_bottom2.setBackgroundColor(Color.rgb(252, 252, 252));
        viewTopLine2.setBackgroundColor(getResources().getColor(R.color.divider_line_color_5));
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        Constant.activityRun = false;
        //保存用户阅读顺序
        SharedPreferenceUtil.saveLocalOrderData(MainHomeActivity.this);
        if (!isFinish) {
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }


    private void refreshScreenSplash() {

        new Thread(new Runnable() {

            @Override
            public void run() {
                JSONObject json = HttpRequestUtil.getJsonObjectFromServer(WMUrlRequest_1_1.getScreenSplashUrl(
                /* ScreenSplashType.DEVICE_IPHONE5 */
                        DeviceUtil.getDeviceTypeAccordingScreen(MainHomeActivity.this)),800,1000);

                if (json != null) {
                    // 获取app启动图
                    final ScreenSplash splash = JsonDataUtil.getScreenSplash(json);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTransitionImageView.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    TMAnalysis.event(MainHomeActivity.this, "SPLASH_ONCLICK_DF");
                                    int object_type = splash.getObject_type();
                                    int object_id = splash.getObject_id();
                                    String url = splash.getSponsoredLink();
                                    Intent intent = new Intent();
                                    if (object_type == ContentType.CONTENT_TYPE_NOVEL) {
                                        NovelDetailsActivity.Companion.startActivity(MainHomeActivity.this,object_id,Intent.FLAG_ACTIVITY_NEW_TASK);
                                    } else if (object_type == ContentType.CONTENT_TYPE_CARTOON) {
                                        intent.putExtra(Constant.CARTOON_ID, String.valueOf(object_id));
                                        new StartActivityUtils(MainHomeActivity.this, intent).toCartoonDesActivity(String.valueOf(object_id));
                                    } else if (object_type == ContentType.CONTENT_TYPE_NOMAL) {
                                        PersonalNoteService.getInstance().enterPersonalNoteDesActivity(MainHomeActivity.this, String.valueOf(object_id), String.valueOf(object_type));
                                    } else if (!TextUtils.isEmpty(url)) {
                                        intent.setClass(MainHomeActivity.this, BrowseActivity.class);
                                        intent.putExtra(Constant.URL, splash.getSponsoredLink());
                                        startActivity(intent);
                                    }
                                }
                            });
                        }
                    });



                    if (splash != null) {
                        if (splash.getObject_type() == Constant.OBJECT_TYPE_AD) {
                            startGDT();
                        }else{
                            runOnUiThread(() -> {
                                mTransitionImageView.setVisibility(View.VISIBLE);
                                GlideUtil.displayImage(mTransitionImageView,splash.getUrl());
                                flGDT.setVisibility(View.GONE);
                            });
                        }

                    }else{
                        startGDT();
                    }

                }else{
                    startGDT();
                }

            }

        }).start();
    }

    private void startGDT() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTransitionImageView.setVisibility(View.GONE);
                flGDT.setVisibility(View.VISIBLE);
                hideTransitionAd(1000);
            }
        });
    }

    private void hideTransitionAd(long delayed) {
        if (mTransitionRelativeLayout != null && mTransitionRelativeLayout.getVisibility() == View.VISIBLE) {

            hideTranslateAnimation = new TranslateAnimation(0, -ScreenUtil2.getScreenWidthPixel(this), 0, 0);
            hideTranslateAnimation.setDuration(700);
            mTransitionRelativeLayout.setVisibility(View.VISIBLE);
            if (mTransitionBackLayout != null) {
                mTransitionBackLayout.setVisibility(View.GONE);
            }
            hideTranslateAnimation.setStartOffset(delayed);
            hideTranslateAnimation.setAnimationListener(new AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    // TODO Auto-generated method stub
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                    // TODO Auto-generated method stub
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    // TODO Auto-generated method stub
                    if (mTransitionImageView != null) {
                        mTransitionRelativeLayout.setVisibility(View.GONE);
                        AccountService.newFunctionGuide(MainHomeActivity.this);
//                        boolean canShowDialog = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean(SPKey.PERMISSION_TIP_DIALOG, getThisActivity(), true);
//                        //获取权限
//                        if (canShowDialog && ActivityCompat.checkSelfPermission(MainHomeActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//                            DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(SPKey.PERMISSION_TIP_DIALOG,false,getThisActivity());
//                            PermissionTipDialog dialog = new PermissionTipDialog(MainHomeActivity.this);
//                            dialog.show();
//                            dialog.setOnBtnClickListener(() -> {
//                                ActivityCompat.requestPermissions(MainHomeActivity.this,
//                                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_PHONE_STATE);
//
//                            });
//                        }else{
//                            getConfig(true);
//                        }
                        getConfig(true);
                    }
                    UpdateUtil.isWifiConnect(MainHomeActivity.this);
                    PushManager.getInstance().inAppMessage(MainHomeActivity.this,InAppMessageKey.MAIN);

                }
            });
            mTransitionRelativeLayout.startAnimation(hideTranslateAnimation);
        }
    }



    private long keyDownLastTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long curTime = System.currentTimeMillis();
            if (curTime - keyDownLastTime > 2000) {
                keyDownLastTime = curTime;
                Toast.makeText(this,"再按一次退出豆花",Toast.LENGTH_LONG).show();
                return false;
            }else{
                keyDownLastTime = 0;
                moveTaskToBack(false);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    public static MainHomeActivity getInstance() {
        return instance;
    }






    /**
     *
     * @param count
     * @param isNative 是否是原生发起
     */
    public void setUnreadNotify(int count,boolean isNative) {
        if (unreadNotify != null) {
            if (count > 0) {
                unreadNotify.setVisibility(View.VISIBLE);
            } else {
                unreadNotify.setVisibility(View.GONE);
            }
        }
        if (isNative) {
            QLXNotificationCenter.getInstance().postNotify("refrushNotice",null);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_READ_PHONE_STATE) {
            if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
            }
            //不论权限是否获取成功，都需要获取服务器信息
            getConfig(true);
        }
    }






}
